package com.bizmda.bizsip.sink.connector;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizResultEnum;
import com.bizmda.bizsip.config.AbstractSinkConfig;
import com.bizmda.bizsip.sink.connector.sinkbean.JSONObjectSinkBeanInterface;
import com.bizmda.bizsip.sink.connector.sinkbean.SinkBeanInterface;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;

/**
 * @author 史正烨
 */
@Slf4j
@Getter
public class SinkBeanSinkConnector extends AbstractSinkConnector {
    private Object sinkBean;
    private String clazzName;
    private boolean isSpringBean = false;


    @Override
    public void init(AbstractSinkConfig sinkConfig) throws BizException {
        super.init(sinkConfig);
        this.clazzName = (String) sinkConfig.getConnectorMap().get("class-name");
        if (sinkConfig.getConnectorMap().get("spring-bean") == null) {
            this.isSpringBean = false;
        }
        else {
            this.isSpringBean = (Boolean) sinkConfig.getConnectorMap().get("spring-bean");
        }
        log.info("初始化JavaSinkConnector:关联类[{}], SpringBean[{}]",this.clazzName,this.isSpringBean);
        try {
            if (this.isSpringBean) {
                sinkBean = SpringUtil.getBean(Class.forName(this.clazzName));
            }
            else {
                sinkBean = Class.forName(this.clazzName).getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException
                | NoSuchMethodException | InvocationTargetException e) {
            log.error("获取类出错",e);
            throw new BizException(BizResultEnum.CONNECTOR_JAVA_CLASS_CREATE_ERROR,e);
        }
    }

    @Override
    public Object process(Object inMessage) throws BizException {
        log.debug("调用SinkBeanSinkConnector[{}]的process()",this.clazzName);
        if (sinkBean instanceof SinkBeanInterface)
        {
            byte[] outMessage = ((SinkBeanInterface) sinkBean).process((byte[])inMessage);
            return outMessage;
        }
        else if (sinkBean instanceof JSONObjectSinkBeanInterface) {
            JSONObject outMessage = ((JSONObjectSinkBeanInterface) sinkBean).process((JSONObject) inMessage);
            return outMessage;
        }
        else {
            throw new BizException(BizResultEnum.CONNECTOR_JAVA_CLASS_CREATE_ERROR,"不是SinkBeanInterface和JSONObjectSinkBeanInterface类型："+this.clazzName);
        }
   }
}
